package jupiter.servlets;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
 
import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.http.HttpSession;

import jupiter.messaging.ApplicationAddressBook;
import jupiter.messaging.Inbox;
import jupiter.messaging.Message;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.mortbay.util.ajax.Continuation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 
 
public class SessionListener implements HttpSessionListener {
	Logger logger = LoggerFactory.getLogger(SessionListener.class);
	
	public void sessionCreated(HttpSessionEvent arg0) {
	}
 
	public void sessionDestroyed(HttpSessionEvent arg0) {
		try{
			logger.info("     Destroying session");
			Inbox i = (Inbox) arg0.getSession().getAttribute("Inbox");
			logger.info("     inbox");
			ApplicationAddressBook.removeInbox(i);
			logger.info("     global");
	
			JSONObject parsed = new JSONObject();
			try {
				parsed.put("type", "user");
				parsed.put("action", "destroy");
				parsed.put("call_id", i.call_id);
				parsed.put("from", i.call_id);
				parsed.put("page", i.page);
				parsed.put("name", i.name);
				parsed.put("website", i.website);
			}catch(JSONException e){
				logger.error("JSONException in SessionListener", e);
			}
			if(i.read_only) return;
			Message message = new Message(parsed.toString());
			Message.subscriber.sendText(message.toString());
		}catch(RuntimeException e){
			logger.error("RuntimeException in MessageServlet", e);
			throw e;
	    }catch(Exception e){
			logger.error("Exception in MessageServlet", e);
	    }
	}
	
 
}